<template>
  <div>
    <el-container class="main-el-contarner">
      <el-aside width="200px" style="padding: 10px" v-show="isShow">
        <div class="aside-warp">
          <div>
            <el-row>
              <el-col :span="7">
                <span style="font-size: 12px; color: #3785ff; font-weight: bold">
                  告警分类
                </span>
              </el-col>
              <el-col :span="17">
                <el-input
                  v-model="filterKeyText"
                  class="w-50 m-2"
                  placeholder="请输入关键字"
                  prefix-icon="el-icon-search"
                  size="mini"
              /></el-col>
            </el-row>
          </div>
          <div style="margin-top: 10px">
            <el-tree
              :data="treeData"
              :load="loadNode"
              :highlight-current="true"
              lazy
              :filter-node-method="filterNode"
              @node-click="handleNodeClick"
              default-expand-all
              ref="treeRef"
            >
              <!--           <span slot-scope="{node, data}">-->
              <!--            {{ data.name }}-->
              <!--           </span>-->
            </el-tree>
          </div>
        </div>
      </el-aside>
      <el-main>
        <div
          style="position: absolute; top: 50%"
          :style="{ left: isShow ? '190px' : '0px' }"
        >
          <div class="showTree" @click="handleShowTree">
            <i :class="isShow ? 'el-icon-arrow-left' : 'el-icon-arrow-right'"></i>
          </div>
        </div>
        <div class="kanbao-bigbox">
          <div class="righttop-search-box">
            <el-form
              :inline="true"
              :model="param"
              label-width="100px"
              @submit.native.prevent
            >
              <el-form-item label="" label-width="10px">
                <el-input
                  placeholder="请输入关键字检索"
                  v-model="param.name"
                  clearable
                  size="small"
                  style="width: 350px"
                  @keyup.enter.native="onSearch"
                >
                  <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="small" @click="onSearch">查找</el-button>
                <el-button type="primary" size="small" @click="onSearchAll"
                  >查看全部</el-button
                >
              </el-form-item>

              <el-form-item style="float: right">
                <el-button type="text" style="color: #18bc9c" @click="handleAdd"
                  ><i class="el-icon-plus"></i> 新增分类</el-button
                >
                <el-button
                  type="text"
                  v-if="selectionChangeData == ''"
                  disabled
                  style="color: #cdc5bf"
                  ><i class="el-icon-delete"></i>删除数据</el-button
                >
                <el-button type="text" v-else style="color: #ff0000" @click="delClick"
                  ><i class="el-icon-delete"></i> 删除数据</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <div class="container-box">
            <el-table
              :data="tabledatas"
              border
              stripe
              max-height="490px"
              :header-cell-style="{
                background: '#cfcfcf',
                color: '#000000',
                'text-align': 'center',
              }"
              :cell-style="{ 'text-align': 'center' }"
              style="width: 100%"
              size="small"
              @selection-change="selectionChange"
            >
              <el-table-column
                type="selection"
                header-align="center"
                width="60"
              ></el-table-column>
              <el-table-column
                type="index"
                label="序号ID"
                :index="indexMethod"
                align="center"
                width="100"
              ></el-table-column>
              <el-table-column prop="category_name" label="名称"> </el-table-column>
              <!--              <el-table-column-->
              <!--                  prop="status"-->
              <!--                  label="状态"-->
              <!--                  width="150">-->
              <!--                <template slot-scope="scope">-->
              <!--                  <font v-if="scope.row.status=='1'">启用</font>-->
              <!--                  <font v-else-if="scope.row.status==='0'">禁用</font>-->
              <!--                  <font v-else>/</font>-->
              <!--                </template>-->
              <!--              </el-table-column>-->

              <el-table-column fixed="right" label="操作" width="150">
                <template slot-scope="scope">
                  <el-button
                    @click="editClick(scope.row)"
                    type="text"
                    icon="el-icon-edit"
                    style="color: #18bc9c; margin: 5px; padding: 0px"
                    >编辑
                  </el-button>
                  <!--                  <el-button @click="delClick(scope.row)" type="text" icon="el-icon-delete"-->
                  <!--                             style="color: #FF0000;margin:5px;padding:0px;">删除-->
                  <!--                  </el-button>-->
                </template>
              </el-table-column>
            </el-table>

            <div class="pagebox">
              <el-pagination
                @size-change="sizeChange"
                @current-change="currentChange"
                :current-page="param.pageNo"
                :page-sizes="[10, 30, 50, 100, 500]"
                :page-size="param.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="dataTotal"
              >
              </el-pagination>
            </div>
          </div>
          <div>
            <el-dialog
              :title="dialogtitle"
              v-if="dialogVisible"
              v-dialogDrag
              :visible.sync="dialogVisible"
              width="70%"
              top="30px"
              :class="dialogVisible == true ? 'action01' : 'action02'"
              :before-close="handleClose"
            >
              <el-form
                :model="fromData.datas[0]"
                :inline="true"
                :rules="rules"
                ref="fromData"
              >
                <el-form-item
                  label="类别名称"
                  :label-width="formLabelWidth"
                  prop="category_name"
                >
                  <el-input
                    v-model="fromData.datas[0].category_name"
                    placeholder="类别名称"
                    style="width: 215px"
                  ></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="save">保 存</el-button>
              </span>
            </el-dialog>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import SideHeader from "@/views/inc/SideHeader";
import Navlanmu from "@/views/inc/Navlanmu";
import LeftMenuMessage from "@/views/inc/LeftMenuMessage";
import { getDateTimes, numFormat, getDateWeek } from "@/utils/index.js";
import { getlist, getTree, getgridsave, getdeletes } from "@/api/message/list";

export default {
  name: "Electricboard",
  components: { SideHeader, Navlanmu, LeftMenuMessage },
  data() {
    return {
      loadingdata1: false,
      filterKeyText: "",
      isloading: false,
      isShow: true,
      param: {
        funId: "msg_alarm_category",
        warnStatus: "",
        name: "",
        pageNo: 1,
        pageSize: 10,
      },
      datas: [
        { name: "故障告警", status: "1" },
        { name: "离线告警", status: "1" },
        { name: "消防告警", status: "1" },
        {
          name: "周界入侵",
          status: "1",
        },
      ],
      dataTotal: 0,
      dialogtitle: "",
      dialogVisible: false,
      formLabelWidth: "130px",
      fromData: {
        funId: "msg_alarm_category",
        is_iot: false,
        datas: [
          {
            category_name: "",
            parentId: "",
          },
        ],
      },
      tabledatas: [],
      selectionChangeData: [],
      treeData: [],
      rules: {
        category_name: [{ required: true, message: "类别名称必填", trigger: "blur" }],
      },
      props: {
        children: "children",
        label: "label",
      },
      currentNode: "",
    };
  },
  async mounted() {
    this.getDatas();
    await this.getTreeData();
  },
  created() {
    this.isloading = false;
  },
  watch: {
    filterKeyText(val) {
      this.$refs.treeRef.filter(val);
    },
  },
  methods: {
    handleShowTree() {
      this.isShow = !this.isShow;
    },
    filterNode(value, data, _node) {
      if (!value) return true;
      return data.label.includes(value);
    },
    getTreeData() {
      getTree("msg_alarm_category", "msg_alarm_category", null).then((res) => {
        this.treeData = res.data.map((item) => {
          return {
            label: item.name,
            id: item.id,
            pid: item.pid,
            children: [],
          };
        });
        // console.log(3333, this.treeData,res)
      });
    },
    loadNode(node, resolve) {
      getTree("msg_alarm_category", "msg_alarm_category", node.data.id).then((res) => {
        // console.log(res.data , node ,this.treeData)
        const child = res.data.map((item) => {
          return {
            label: item.name,
            id: item.id,
            pid: item.pid,
          };
        });

        resolve(child);
        // this.treeData = [...this.treeData];
        // this.treeData = this.treeData.filter(item=>{
        //   return res.data.pid === node.data.id
        // })

        // resolve(this.treeData)
        // resolve()
      });
    },
    handleNodeClick(data) {
      this.currentNode = data.id;
      let params = {
        funId: "msg_alarm_category",
        warnStatus: "",
        name: "",
        pageNo: 1,
        pageSize: 10,
        baseSQL:
          "parent_id" +
          "=" +
          `\'${data.id}\'` +
          "or " +
          "category_id" +
          "=" +
          `\'${data.id}\'`,
      };
      getlist(params).then((res) => {
        this.tabledatas = res.data.rows;
      });
    },
    editClick(e) {
      console.log(e);
      // this.getDatas()
      if (this.$refs["fromData"]) {
        this.$refs["fromData"].resetFields();
      }
      this.dialogtitle = "修改分类";
      this.dialogVisible = true;
      this.fromData.datas[0] = e;
      sessionStorage.setItem("initForm", JSON.stringify(this.fromData.datas[0]));
    },
    delClick() {
      // console.log('info',info)

      let tablefromdata = {
        funId: "msg_alarm_category",
        ids: "",
      };

      this.selectionChangeData.forEach((item) => {
        tablefromdata.ids += item.category_id + ";";
      });

      this.$confirm(`已选择${this.selectionChangeData.length}条数据, 是否删除?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        getdeletes(tablefromdata).then((res) => {
          // if(res.status=='200'){
          if (res.data.code == "200") {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.getDatas();
            this.getTreeData();
          } else {
            this.$message({
              message: "删除失败",
              type: "error",
            });
          }
          // }
          // else{
          //   this.$message({
          //       message: '删除告警失败',
          //       type: 'error'
          //   });
          //}
        });
      });
    },
    handleClose() {
      let num = 0;
      for (const key in this.fromData.datas[0]) {
        if (this.fromData.datas[0][key] == "") {
          // num = num + 0
          num += 0;
        } else if (this.fromData.datas[0][key] == null) {
          // num = num + 0
          num += 0;
        } else {
          // num = num + 1
          num += 1;
        }
      }

      if (this.dialogtitle == "新增分类") {
        if (num != 0) {
          this.$confirm("表单未保存,是否关闭?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.dialogVisible = false;
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "取消关闭",
              });
            });
        } else {
          this.dialogVisible = false;
        }
      } else {
        if (
          JSON.stringify(this.fromData.datas[0]) == sessionStorage.getItem("initForm")
        ) {
          this.dialogVisible = false;
        } else {
          this.$confirm("表单未保存,是否关闭?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.dialogVisible = false;
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "取消关闭",
              });
            });
        }
      }
    },
    //保存按钮
    save() {
      this.$refs["fromData"].validate((valid) => {
        if (valid) {
          // ('valid',valid)
          console.log(423, this.fromData.datas[0]);
          if (this.fromData.datas[0].category_id) {
            this.updateaction();
            this.dialogVisible = false;
          } else {
            this.addaction();
            this.dialogVisible = false;
          }
        }
      });
    },
    updateaction() {
      getgridsave(this.fromData).then((res) => {
        if (res.data.code == "200") {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.getDatas();
          this.getTreeData();
        } else {
          this.$message({
            message: "修改失败",
            type: "error",
          });
        }
      });
    },
    //添加数据
    addaction() {
      if (this.currentNode === "") {
        this.fromData.datas[0].parent_id = null;
      } else {
        this.fromData.datas[0].parent_id = this.currentNode;
      }
      getgridsave(this.fromData).then((res) => {
        if (res.data.code == "200") {
          this.$message({
            message: "添加成功",
            type: "success",
          });
          this.getDatas();
          this.getTreeData();
        } else {
          this.$message({
            message: "添加失败",
            type: "error",
          });
        }
      });
    },
    nodeClick(type, data) {
      this.loadingdata1 = true;
      this.searchForm = data;
      this.getEnergyQushi();
      this.getEnergyDeptRanking();
      this.getEnergylevelCount();
    },
    handleAdd() {
      if (this.$refs["fromData"]) {
        this.$refs["fromData"].resetFields();
      }
      this.handleRest();
      // this.fromData.datas[0].category_name = ''
      // this.fromData.datas[0].parentId = ''
      this.dialogtitle = "新增分类";
      this.dialogVisible = true;
    },
    // 表单重置
    handleRest() {
      this.fromData = {
        funId: "msg_alarm_category",
        is_iot: false,
        datas: [
          {
            category_name: "",
            parentId: "",
          },
        ],
      };
    },
    // 数据搜索按钮
    onSearch() {
      this.param.pageNo = 1;
      this.getDatas();
    },

    onSearchAll() {
      this.param.baseSQL = "";
      getlist(this.param).then((res) => {
        if (res.status == "200") {
          let resdata = res.data;
          this.tabledatas = resdata.rows;
          this.dataTotal = resdata.total;
          // console.log('this.tabledatas',this.tabledatas)
        }
      });
    },
    // 复选框按钮
    selectionChange(e) {
      this.selectionChangeData = e;
    },
    indexMethod(index) {
      return (this.param.pageNo - 1) * this.param.pageSize + index + 1;
    },
    sizeChange(val) {
      this.param.pageSize = val;
      this.getDatas();
    },
    currentChange(val) {
      this.param.pageNo = val;
      this.getDatas();
    },
    getDatas() {
      if (
        this.param.warnStatus == "" &&
        this.param.name == "" &&
        this.currentNode == ""
      ) {
        // this.currentNode =null
        this.param.baseSQL = "";
      } else {
        this.param.baseSQL =
          'category_name like "%' +
          this.param.name +
          '%"' +
          " and " +
          "parent_id" +
          "=" +
          `\'${this.currentNode}\'`;
      }
      // axios.post('http://192.168.10.238:8098/msg/list',this.param).then(res=>{
      //   let resdata = res.data
      //   this.tabledatas = resdata.rows
      //   this.dataTotal = resdata.total
      // })
      getlist(this.param).then((res) => {
        if (res.status == "200") {
          let resdata = res.data;
          this.tabledatas = resdata.rows;
          this.dataTotal = resdata.total;
          // console.log('this.tabledatas',this.tabledatas)
        }
      });
    },
  },
};
</script>
<style>
.kanbao-bigbox .el-loading-spinner .el-loading-text {
  color: #666 !important;
}
</style>
<style scoped>
.el-main {
  padding: 0px !important;
  .showTree {
    width: 15px;
    height: 50px;
    border: 1px #dfdfdf solid;
    line-height: 50px;
    border-top-right-radius: 15px;
    border-bottom-right-radius: 15px;
    text-align: center;
    cursor: pointer;
    &:hover {
      background-color: #007dff;
      color: #fff;
    }
  }
}

.kanbao-bigbox {
  margin-top: 0px;
  padding-left: 10px;
}
</style>
<style scoped>
.aside-warp {
  /* height: calc(100vh - 150px); */
  height: calc(100% - 80px);
  border: #ececec 1px solid;
}
.righttop-search-box {
  background: #f8f8f8;
  padding: 8px 20px 7px 20px;
  border-bottom: 1px solid #ececec;
  position: fixed;
  top: 0;
  width: calc(100% - 256px);
  z-index: 4;
}

.righttop-search-box .el-form-item {
  margin-bottom: 0px !important;
}

.container-box {
  padding: 10px;
  margin: 50px 0;
}

.pagebox {
  text-align: right;
  padding: 10px;
  position: fixed;
  bottom: 0;
  right: 0;
  width: 100%;
  background-color: #ececec;
  z-index: 4;
}
</style>
